package com.foryou.wechat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.foryou.wechat.common.Constants;
import com.foryou.wechat.common.enums.ImageTypeEnum;
import com.foryou.wechat.entity.*;
import com.foryou.wechat.mapper.*;
import com.foryou.wechat.model.Query;
import com.foryou.wechat.model.dto.PlaceDTO;
import com.foryou.wechat.model.vo.PlaceActionVo;
import com.foryou.wechat.model.vo.PlaceCommentItem;
import com.foryou.wechat.model.vo.PlaceVo;
import com.foryou.wechat.model.vo.UserVo;
import com.foryou.wechat.service.PlaceService;
import com.foryou.wechat.service.UserFollowService;
import com.foryou.wechat.service.UserImageService;
import com.foryou.wechat.service.UserService;
import com.foryou.wechat.utils.HttpContextUtils;
import com.foryou.wechat.utils.Response;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * Created by Lee.
 */
@Service
public class PlaceServiceImpl implements PlaceService {

    private final PlaceMapper placeMapper;

    private final PlaceCollectMapper placeCollectMapper;

    private final PlaceClockMapper placeClockMapper;

    private final PlaceCommentMapper placeCommentMapper;

    private final UserImageService imageService;

    private final SubjectMapper subjectMapper;

    private final UserFollowService userFollowService;

    private final PlaceTypeMapper placeTypeMapper;
    private final UserService userService;


    public PlaceServiceImpl(PlaceMapper placeMapper, PlaceCollectMapper placeCollectMapper, PlaceClockMapper placeClockMapper, PlaceCommentMapper placeCommentMapper, UserImageService imageService, SubjectMapper subjectMapper, UserFollowService userFollowService, PlaceTypeMapper placeTypeMapper, UserService userService) {
        this.placeMapper = placeMapper;
        this.placeCollectMapper = placeCollectMapper;
        this.placeClockMapper = placeClockMapper;
        this.placeCommentMapper = placeCommentMapper;
        this.imageService = imageService;
        this.subjectMapper = subjectMapper;
        this.userFollowService = userFollowService;
        this.placeTypeMapper = placeTypeMapper;
        this.userService = userService;
    }

    @Override
    @Transactional
    public Response addPlace(PlaceDTO placeDTO) {
        Long userSessionId = HttpContextUtils.getUserId();
        boolean checkResult = userService.checkUserInfo(userSessionId);
        if (!checkResult) {
            return Response.failure(Constants.EDIT_USER_INFO);
        }
        PlaceEntity placeEntity = new PlaceEntity(
                placeDTO.getPlaceName(),
                placeDTO.getPlaceIntro(),
                placeDTO.getPlaceAddress(),
                placeDTO.getPlaceTypeId(),
                placeDTO.getRegion(),
                placeDTO.getSubjectIds(),
                userSessionId
        );
        int result = placeMapper.insert(placeEntity);
        if (result > 0) {
            return Response.success(placeEntity.getId());
        }
        return Response.failure(Constants.OPERATION_FAILURE);
    }

    @Override
    public Response getPlaceDetail(Long placeId) {
        //TODO
        Long sessionUserId = HttpContextUtils.getUserId();
        //1.得到发布的场地信息
        PlaceEntity placeEntity = placeMapper.selectById(placeId);
        //地址
        //得到场地类别信息
        PlaceTypeEntity placeTypeEntity = placeTypeMapper.selectById(placeEntity.getPlaceTypeId());
        String[] region = placeEntity.getRegion().split(" ");
        //2.得到发布的图片信息集合
        List<String> imageUrlList = imageService.imageUrlList(placeId, ImageTypeEnum.FILED);
        //3.得到发布的主题信息集合
        List<String> subjectList = subjectMapper.getSubjectList(placeEntity.getSubjectIds().split(","));

        //组装用户信息
        UserVo userVo = userFollowService.getUserVo(placeEntity.getUserId());

        PlaceCollectEntity collectEntity = placeCollectMapper.selectOne(
                new QueryWrapper<PlaceCollectEntity>()
                .eq("user_id", sessionUserId)
                .eq("place_id", placeId)
        );
        boolean isCollect = !ObjectUtils.isEmpty(collectEntity);
        boolean isClock = placeClockMapper.getUserPlaceClock(placeId,sessionUserId)>0;
        boolean isOwner = placeEntity.getUserId().equals(sessionUserId);

        //7.得到签到的用户集合头像
        List<String> userAvatarUrlList = placeClockMapper.getUserAvatarUrlList(placeId);
        //8.得到评论的列表
        List<PlaceCommentItem> commentList = placeCommentMapper.getPlaceCommentList(placeId);

        //9.组装数据
        return Response.success(new PlaceVo(
                placeId,
                imageUrlList.get(0),
                placeEntity.getPlaceName(),
                region,
                placeEntity.getPlaceAddress(),
                placeTypeEntity.getName(),
                placeEntity.getPlaceIntro(),
                imageUrlList,
                subjectList,
                isCollect,
                isClock,
                userVo,
                DateFormatUtils.format(placeEntity.getCreateTime(), Constants.DATE_FORMAT_PATTERN_CH),
                userAvatarUrlList,
                commentList,
                isOwner,
                placeEntity.getScore(),
                placeEntity.getAuditStatus()
        ));
    }

    @Override
    public Response collectPlace(Long placeId) {

        // TODO
        Long sessionUserId = HttpContextUtils.getUserId();
        placeCollectMapper.insert(new PlaceCollectEntity(sessionUserId,placeId));
        return Response.success();
    }

    @Override
    public Response cancelPlace(Long placeId) {
        placeCollectMapper.deletePlaceClock(placeId, HttpContextUtils.getUserId());
        return Response.success();
    }

    @Override
    public Response clockPlace(Long placeId) {
        // TODO
        Long sessionUserId = HttpContextUtils.getUserId();
        PlaceCollectEntity placeCollect = placeCollectMapper.getUserPlaceCollect(placeId, sessionUserId);
        if (!ObjectUtils.isEmpty(placeCollect)) {
            return Response.failure("已打卡，无需重复打卡！");
        }
        placeClockMapper.insert(new PlaceClockEntity(sessionUserId, placeId));
        //7.得到签到的用户集合头像
        List<String> userAvatarUrlList = placeClockMapper.getUserAvatarUrlList(placeId);
        return Response.success(userAvatarUrlList);
    }

    @Override
    public Response commentPlace(Long placeId, String content) {
        Long sessionUserId = HttpContextUtils.getUserId();
        PlaceEntity placeEntity = placeMapper.selectById(placeId);
        if (ObjectUtils.isEmpty(placeEntity)) {
            return Response.failure(Constants.OPERATION_FAILURE);
        }
        if (!StringUtils.isNotBlank(content)) {
            return Response.failure("请填写评论内容！");
        }
        int insert = placeCommentMapper.insert(new PlaceCommentEntity(placeId, sessionUserId, content));
        if (insert > 0) {
            //8.得到评论的列表
            List<PlaceCommentItem> commentList = placeCommentMapper.getPlaceCommentList(placeId);
            return Response.success(commentList);
        }
        return Response.failure(Constants.OPERATION_FAILURE);
    }

    @Override
    public Response getPlaceList(Query query) {
        List<PlaceActionVo> placeActionVoList = placeMapper.queryPlaceList(query);
        placeActionVoList.forEach(e->{
            e.setAddress(e.getRegion().split(" "));
            e.setDefaultImageUrl(imageService.imageUrlList(e.getPlaceId(), ImageTypeEnum.FILED).get(0));
        });
        return Response.success(placeActionVoList);
    }

    @Override
    public Response queryCollectPlaceList(int start, Long userId) {
        List<PlaceActionVo> placeActionVoList = placeMapper.queryCollectPlaceList(start, userId);
        placeActionVoList.forEach(e->{
            e.setAddress(e.getRegion().split(" "));
            e.setDefaultImageUrl(imageService.imageUrlList(e.getPlaceId(), ImageTypeEnum.FILED).get(0));
        });
        return Response.success(placeActionVoList);
    }

}
